import { ref } from 'vue'
import store from '@/store'
import { defineStore } from 'pinia'
import { type RouteRecordRaw } from 'vue-router'
import { constantRoutes, asyncRoutes } from '@/router'
// import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from '@/config/route'
import { RoleType } from '@/types/enum'

const hasPermission = (role: RoleType, route: RouteRecordRaw) => {
  const routeRoles = route.meta?.role
  return routeRoles ? role == routeRoles : true
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], role: RoleType) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }
    if (hasPermission(role, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterAsyncRoutes(tempRoute.children, role)
      }
      res.push(tempRoute)
    }
  })
  return res
}

const ArrangeMenuPosition = (
  constantRoutes: RouteRecordRaw[],
  accessedRoutes: RouteRecordRaw[]
) => {
  accessedRoutes.forEach((item) => {
    const index = constantRoutes.findIndex((i) => i.path === item.path)
    if (index < 0) {
      if (item.meta?.position) {
        constantRoutes.splice(item.meta.position, 0, item)
      } else {
        constantRoutes.push(item)
      }
    }
  })
}

export const usePermissionStore = defineStore(
  'permission',
  () => {
    const routes = ref<RouteRecordRaw[]>([])
    const dynamicRoutes = ref<RouteRecordRaw[]>([])
    const isDynamicRoutesAdded = ref<boolean>(false)
    const setRoutes = (role: RoleType) => {
      const accessedRoutes = routeSettings.async
        ? filterAsyncRoutes(asyncRoutes, role)
        : asyncRoutes
      ArrangeMenuPosition(constantRoutes, accessedRoutes)
      routes.value = constantRoutes
      dynamicRoutes.value = accessedRoutes
    }

    return { routes, dynamicRoutes, setRoutes, isDynamicRoutesAdded }
  },
  {
    persist: true
  }
)

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
